{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Distributed data parallel MaskRCNN training with TensorFlow2 and SMDataParallel\n",
    "\n",
    "SMDataParallel is a new capability in Amazon SageMaker to train deep learning models faster and cheaper. SMDataParallel is a distributed data parallel training framework for TensorFlow, PyTorch, and MXNet.\n",
    "\n",
    "This notebook example shows how to use SMDataParallel with TensorFlow(version 2.3.1) on [Amazon SageMaker](https://aws.amazon.com/sagemaker/) to train a MaskRCNN model on [COCO 2017 dataset](https://cocodataset.org/#home) using [Amazon FSx for Lustre file-system](https://aws.amazon.com/fsx/lustre/) as data source.\n",
    "\n",
    "The outline of steps is as follows:\n",
    "\n",
    "1. Stage COCO 2017 dataset in [Amazon S3](https://aws.amazon.com/s3/)\n",
    "2. Create Amazon FSx Lustre file-system and import data into the file-system from S3\n",
    "3. Build Docker training image and push it to [Amazon ECR](https://aws.amazon.com/ecr/)\n",
    "4. Configure data input channels for SageMaker\n",
    "5. Configure hyper-prarameters\n",
    "6. Define training metrics\n",
    "7. Define training job, set distribution strategy to SMDataParallel and start training\n",
    "\n",
    "**NOTE:**  With large traning dataset, we recommend using (Amazon FSx)[https://aws.amazon.com/fsx/] as the input filesystem for the SageMaker training job. FSx file input to SageMaker significantly cuts down training start up time on SageMaker because it avoids downloading the training data each time you start the training job (as done with S3 input for SageMaker training job) and provides good data read throughput.\n",
    "\n",
    "\n",
    "**NOTE:** This example requires SageMaker Python SDK v2.X."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Amazon SageMaker Initialization\n",
    "\n",
    "Initialize the notebook instance. Get the aws region, sagemaker execution role.\n",
    "\n",
    "The IAM role arn used to give training and hosting access to your data. See the [Amazon SageMaker Roles](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the sagemaker.get_execution_role() with the appropriate full IAM role arn string(s). As described above, since we will be using FSx, please make sure to attach `FSx Access` permission to this IAM role."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "! python3 -m pip install --upgrade sagemaker\n",
    "import sagemaker\n",
    "from sagemaker import get_execution_role\n",
    "from sagemaker.estimator import Estimator\n",
    "import boto3\n",
    "\n",
    "sagemaker_session = sagemaker.Session()\n",
    "bucket = sagemaker_session.default_bucket()\n",
    "\n",
    "role = get_execution_role() # provide a pre-existing role ARN as an alternative to creating a new role\n",
    "print(f'SageMaker Execution Role:{role}')\n",
    "\n",
    "client = boto3.client('sts')\n",
    "account = client.get_caller_identity()['Account']\n",
    "print(f'AWS account:{account}')\n",
    "\n",
    "session = boto3.session.Session()\n",
    "region = session.region_name\n",
    "print(f'AWS region:{region}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prepare SageMaker Training Images\n",
    "\n",
    "1. SageMaker by default use the latest [Amazon Deep Learning Container Images (DLC)](https://github.com/aws/deep-learning-containers/blob/master/available_images.md) TensorFlow training image. In this step, we use it as a base image and install additional dependencies required for training MaskRCNN model.\n",
    "2. In the Github repository https://github.com/HerringForks/DeepLearningExamples.git we have made TensorFlow-SMDataParallel MaskRCNN training script available for your use. We will be installing the same on the training image.\n",
    "\n",
    "### Build and Push Docker Image to ECR\n",
    "\n",
    "Run the below command build the docker image and push it to ECR."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = \"<IMAGE_NAME>\"  # Example: tf2-mask-rcnn-smdataparallel-sagemaker\n",
    "tag = \"<IMAGE_TAG>\"   # Example: latest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pygmentize ./Dockerfile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pygmentize ./build_and_push.sh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "! chmod +x build_and_push.sh; bash build_and_push.sh {region} {image} {tag}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparing FSx Input for SageMaker\n",
    "\n",
    "1. Download and prepare your training dataset on S3.\n",
    "2. Follow the steps listed here to create a FSx linked with your S3 bucket with training data - https://docs.aws.amazon.com/fsx/latest/LustreGuide/create-fs-linked-data-repo.html. Make sure to add an endpoint to your VPC allowing S3 access.\n",
    "3. Follow the steps listed here to configure your SageMaker training job to use FSx https://aws.amazon.com/blogs/machine-learning/speed-up-training-on-amazon-sagemaker-using-amazon-efs-or-amazon-fsx-for-lustre-file-systems/\n",
    "\n",
    "### Important Caveats\n",
    "\n",
    "1. You need use the same `subnet` and `vpc` and `security group` used with FSx when launching the SageMaker notebook instance. The same configurations will be used by your SageMaker training job.\n",
    "2. Make sure you set appropriate inbound/output rules in the `security group`. Specically, opening up these ports is necessary for SageMaker to access the FSx filesystem in the training job. https://docs.aws.amazon.com/fsx/latest/LustreGuide/limit-access-security-groups.html\n",
    "3. Make sure `SageMaker IAM Role` used to launch this SageMaker training job has access to `AmazonFSx`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SageMaker TensorFlow Estimator function options\n",
    "\n",
    "In the following code block, you can update the estimator function to use a different instance type, instance count, and distrubtion strategy. You're also passing in the training script you reviewed in the previous cell.\n",
    "\n",
    "**Instance types**\n",
    "\n",
    "SMDataParallel supports model training on SageMaker with the following instance types only:\n",
    "1. ml.p3.16xlarge\n",
    "1. ml.p3dn.24xlarge [Recommended]\n",
    "1. ml.p4d.24xlarge [Recommended]\n",
    "\n",
    "**Instance count**\n",
    "\n",
    "To get the best performance and the most out of SMDataParallel, you should use at least 2 instances, but you can also use 1 for testing this example.\n",
    "\n",
    "**Distribution strategy**\n",
    "\n",
    "Note that to use DDP mode, you update the the `distribution` strategy, and set it to use `smdistributed dataparallel`.\n",
    "\n",
    "### Training script\n",
    "\n",
    "In the Github repository https://github.com/HerringForks/DeepLearningExamples.git we have made reference TensorFlow-SMDataParallel MaskRCNN training script available for your use. Clone the repository."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Clone herring (smdataparallel) forks repository for reference implementation of H\n",
    "!rm -rf DeepLearningExamples\n",
    "!git clone --recursive https://github.com/HerringForks/DeepLearningExamples.git"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker.tensorflow import TensorFlow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "instance_type = \"ml.p3dn.24xlarge\" # Other supported instance type: ml.p3.16xlarge\n",
    "instance_count = 2 # You can use 2, 4, 8 etc.\n",
    "docker_image = f\"{account}.dkr.ecr.{region}.amazonaws.com/{image}:{tag}\" # YOUR_ECR_IMAGE_BUILT_WITH_ABOVE_DOCKER_FILE\n",
    "username = 'AWS'\n",
    "subnets = ['<SUBNET_ID>'] # Should be same as Subnet used for FSx. Example: subnet-0f9XXXX\n",
    "security_group_ids = ['<SECURITY_GROUP_ID>'] # Should be same as Security group used for FSx. sg-03ZZZZZZ\n",
    "job_name = 'tf2-smdataparallel-mrcnn-fsx' # This job name is used as prefix to the sagemaker training job. Makes it easy for your look for your training job in SageMaker Training job console.\n",
    "file_system_id='<FSX_ID>' # FSx file system ID with your training dataset. Example: 'fs-0bYYYYYY'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SM_DATA_ROOT = '/opt/ml/input/data/train'\n",
    "\n",
    "hyperparameters={\n",
    "    \"mode\": \"train\",\n",
    "    \"checkpoint\": '/'.join([SM_DATA_ROOT, 'model/resnet/resnet-nhwc-2018-02-07/model.ckpt-112603']), \n",
    "    \"eval_samples\": 5000,\n",
    "    \"init_learning_rate\": 0.04, \n",
    "    \"learning_rate_steps\": \"3750,5000\", \n",
    "    \"model_dir\": \"/opt/ml/code/checkpoints/tensorflow_mask_rcnn\", \n",
    "    \"num_steps_per_eval\": 462,\n",
    "    \"total_steps\": 500,\n",
    "    \"train_batch_size\": 4,\n",
    "    \"eval_batch_size\": 8,\n",
    "    \"training_file_pattern\": '/'.join([SM_DATA_ROOT, 'train']), \n",
    "    \"validation_file_pattern\": '/'.join([SM_DATA_ROOT, 'val']), \n",
    "    \"val_json_file\": '/'.join([SM_DATA_ROOT, 'annotations/instances_val2017.json']),    \n",
    "    \"amp\": '',\n",
    "    \"use_batched_nms\": '',\n",
    "    \"xla\": '',\n",
    "    \"nouse_custom_box_proposals_op\": '',\n",
    "    \"seed\": 987\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "estimator = TensorFlow(entry_point='DeepLearningExamples/TensorFlow2/Segmentation/MaskRCNN/mask_rcnn_sm.py',\n",
    "                        role=role,\n",
    "                        image_uri=docker_image,\n",
    "                        source_dir='.',\n",
    "                        framework_version='2.3.1',\n",
    "                        py_version='py3',\n",
    "                        instance_count=instance_count,\n",
    "                        instance_type=instance_type,\n",
    "                        sagemaker_session=sagemaker_session,\n",
    "                        subnets=subnets,\n",
    "                        hyperparameters=hyperparameters,\n",
    "                        security_group_ids=security_group_ids,\n",
    "                        debugger_hook_config=False,\n",
    "                        # Training using SMDataParallel Distributed Training Framework\n",
    "                        distribution={'smdistributed':{\n",
    "                                            'dataparallel':{\n",
    "                                                    'enabled': True\n",
    "                                                 }\n",
    "                                          }\n",
    "                                      }\n",
    "                      )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure FSx Input for your SageMaker Training job\n",
    "\n",
    "from sagemaker.inputs import FileSystemInput\n",
    "file_system_directory_path='YOUR_MOUNT_PATH_FOR_TRAINING_DATA' # NOTE: '/fsx/' will be the root mount path. Example: '/fsx/mask_rcnn/PyTorch'\n",
    "file_system_access_mode='rw'\n",
    "file_system_type='FSxLustre'\n",
    "train_fs = FileSystemInput(file_system_id=file_system_id,\n",
    "                                    file_system_type=file_system_type,\n",
    "                                    directory_path=file_system_directory_path,\n",
    "                                    file_system_access_mode=file_system_access_mode)\n",
    "data_channels = {'train': train_fs}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Submit SageMaker training job\n",
    "estimator.fit(inputs=data_channels, job_name=job_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Additional Resources\n",
    "\n",
    "If you are a new user of Amazon SageMaker, you may find the following helpful to understand how SageMaker uses Docker to train custom models.\n",
    "* To learn more about using Amazon SageMaker with your own training image, see [Use Your Own Training Algorithms\n",
    "](https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html).\n",
    "\n",
    "* To learn more about using Docker to train your own models with Amazon SageMaker, see [Example Notebooks: Use Your Own Algorithm or Model](https://docs.aws.amazon.com/sagemaker/latest/dg/adv-bring-own-examples.html).\n",
    "* To see other examples of distributed training using Amazon SageMaker and TensorFlow, see [Distributed TensorFlow training using Amazon SageMaker\n",
    "](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality/distributed_tensorflow_mask_rcnn)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_tensorflow_p36",
   "language": "python",
   "name": "conda_tensorflow_p36"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}